package vn.com.epi.sevlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Strings;

import vn.com.epi.web.Application;

/**
 * Servlet implementation class UploadLogServlet
 */
@WebServlet(name = "upload-log", description = "Receive log rows from front-end server", urlPatterns = { "/upload-log" })
public class UploadLogServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadLogServlet() {
        super();
    }

    @Override
    public void init() throws ServletException {

    }

    @SuppressWarnings({ "unused" })
    private boolean isValidLog(String line) {
        try {
            String[] chunks = line.split(",");
            long timestamp = Long.parseLong(chunks[0]);
            if (Strings.isNullOrEmpty(chunks[1]))
                return false;
            int actionId = Integer.parseInt(chunks[2].substring(3,
                    chunks[2].length()));
            if (actionId < 0 || 5 < actionId)
                return false;
            int articleID = Integer.parseInt(chunks[3]);
            int categoryID = Integer.parseInt(chunks[4]);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private String getValidLogs(String lines) {
        String logs = "";
        String[] lineArr = lines.split("\r?\n");
        for (int i = 0; i < lineArr.length; i++)
            if (isValidLog(lineArr[i])) {
                if (!Strings.isNullOrEmpty(logs))
                    logs += "\n";
                logs += lineArr[i];
            }
        return logs;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/upload-log-form.jsp").forward(
                req, resp);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            String lines = request.getParameter("content");
            String logs = getValidLogs(lines);
            if (!Strings.isNullOrEmpty(logs)) {
                String[] lineArr = logs.split("\n");
                Application.getLogBuffer().add(getServletContext(), lineArr);
                request.setAttribute("message", "Processed " + lineArr.length + " lines.");
                request.getRequestDispatcher("/WEB-INF/jsp/result-form.jsp")
                        .forward(request, response);
            } else
                response.getWriter().write("Invalid log lines.");
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

}
